package com.sgidi.einvoice.service;

import org.apache.poi.openxml4j.util.ZipSecureFile;
import org.apache.poi.util.Units;
import org.apache.poi.xwpf.usermodel.*;
import org.apache.xmlbeans.XmlException;
import org.openxmlformats.schemas.drawingml.x2006.main.CTGraphicalObject;
import org.openxmlformats.schemas.drawingml.x2006.wordprocessingDrawing.CTAnchor;
import org.openxmlformats.schemas.wordprocessingml.x2006.main.CTDrawing;
import org.springframework.web.multipart.MultipartFile;

import java.io.*;
import java.net.URL;

public class WordSigner {
    public static ByteArrayOutputStream SignWord(MultipartFile wordFile, String PartyIdCount,String keyword,boolean isPersonName) {
        ByteArrayOutputStream out = null;
        try {
            ZipSecureFile.setMinInflateRatio(0.0001);  // 调整为略低于0.01
            // 读取 Word 文档
            XWPFDocument document = new XWPFDocument(wordFile.getInputStream());

            // 在文档中查找核准人
            String approver = keyword+(isPersonName?"":"："); // 指定核准人名称
            int skipCharacters = 3; // 跳过字符数
            String shr = "审核人：";
            boolean foundshr = false;
            int x =0;//固定x轴位置
            for (XWPFParagraph paragraph : document.getParagraphs()) {
                String text = paragraph.getText();
                String normalizedText = text.replaceAll("\\s", ""); // 去掉所有空格
                if (normalizedText.contains(shr)) {
                    int approverIndex = normalizedText.indexOf(shr);
                    if (approverIndex == -1) continue; // 确保找到
                    // 2. 计算页面和段落布局参数（假设A4纸，页边距2cm）
                    int pageWidthEMU = (int) (21.0 * 28.35 * 12700); // 21cm → EMU
                    int marginEMU = (int) (2.0 * 28.35 * 12700);     // 2cm → EMU
                    int paragraphWidthEMU = pageWidthEMU - 2 * marginEMU;
                    // 2. 计算 `approver` 的结束位置 + 3 个字符
                    int insertPos = calculateVisualWidth(text)/2 + paragraphWidthEMU/2 +5*8*12700; // 防止越界
                    x =insertPos;
                    foundshr = true;
                    break;
                }
            }

            boolean found = false;
            for (XWPFParagraph paragraph : document.getParagraphs()) {
                String text = paragraph.getText();
                String normalizedText = text.replaceAll("\\s", ""); // 去掉所有空格
                if (normalizedText.contains(approver)) {
                    // 1. 找到 `approver` 在原始文本中的位置
                    int approverIndex = normalizedText.indexOf(approver);
                    if (approverIndex == -1) continue; // 确保找到
                    // 2. 计算页面和段落布局参数（假设A4纸，页边距2cm）
                    int pageWidthEMU = (int) (21.0 * 28.35 * 12700); // 21cm → EMU
                    int marginEMU = (int) (2.0 * 28.35 * 12700);     // 2cm → EMU
                    int paragraphWidthEMU = pageWidthEMU - 2 * marginEMU;
                    // 2. 计算 `approver` 的结束位置 + 3 个字符
                    //int insertPos = calculateVisualWidth(text)/2 + paragraphWidthEMU/2 +3*8*12700; // 防止越界
                    int y = -10*12700; // y 坐标（0 表示与文本同一行）
                    // 5. 插入图片（浮动方式）
                    XWPFRun pictureRun = paragraph.createRun();
                    String imageURL = "http://192.168.2.8/sgidi/signpic/lynew/" + PartyIdCount + ".png";
                    InputStream inputStream = new URL(imageURL).openStream();
                    pictureRun.addPicture(
                            inputStream, Document.PICTURE_TYPE_JPEG, "signature.jpg",
                            Units.toEMU(70), Units.toEMU(35)); // 图片大小
                    // 6. 将图片从 `inline` 改为 `floating`（浮动）
                    CTDrawing drawing = pictureRun.getCTR().getDrawingArray(0);
                    CTGraphicalObject graphicalObject = drawing.getInlineArray(0).getGraphic();
                    CTAnchor anchor = getAnchorWithGraphic(
                            graphicalObject, "Generated",
                            Units.toEMU(70), Units.toEMU(35), // 图片大小
                            x, y, false // x, y 坐标
                    );
                    System.out.println("approver位置: " + approverIndex);
                    System.out.println("图片X坐标: " + x / 12700 + "pt");
                    drawing.setAnchorArray(new CTAnchor[]{anchor}); // 设置浮动属性
                    drawing.removeInline(0); // 删除行内属性

                    found = true;
                    break;
                }
            }


            if (!found) {
                System.out.println("核准人未找到！");
            }

            // 保存修改后的 Word 文档
            out = new ByteArrayOutputStream();
            document.write(out);
            out.close();
            document.close();

            System.out.println("签名图片已插入成功！");

        } catch (Exception e) {
            e.printStackTrace();
        }
        return out;
    }
    private static int calculateVisualWidth(String text) {
        int totalWidth = 0;
        for (char c : text.toCharArray()) {
            // 判断字符类型（中文/英文/空格）
            int charWidthPt;
            if (Character.isWhitespace(c)) {
                charWidthPt = 8; // 空格宽度设为8pt（假设为英文字符一半）
            } else if (isChinese(c)) {
                charWidthPt = 16; // 中文字符宽度16pt
            } else {
                charWidthPt = 8;  // 英文字符宽度8pt
            }
            totalWidth += charWidthPt * 12700; // 转换为EMU
        }
        return totalWidth;
    }

    private static boolean isChinese(char c) {
        return Character.UnicodeScript.of(c) == Character.UnicodeScript.HAN;
    }
    public static void SignWord1(MultipartFile wordFile, String PartyIdCount, String keyword) {
        try {
            // 读取 Word 文档
            XWPFDocument document = new XWPFDocument(wordFile.getInputStream());

            // 在文档中查找核准人
            String approver = keyword + "："; // 指定核准人名称
            //int skipCharacters = 3; // 跳过字符数
            boolean found = false;
            for (XWPFParagraph paragraph : document.getParagraphs()) {
                String text = paragraph.getText();
                if (text.contains(approver)) {
                    // 找到核准人后跳过指定数量的字符
                    //int index = text.indexOf(approver) + approver.length() + skipCharacters;

                    // 创建一个新的段落来模拟文本框
                    XWPFParagraph textBoxParagraph = document.createParagraph();
                    XWPFRun textBoxRun = textBoxParagraph.createRun();

                    // 拷贝剩余的文本到新段落中
                    //String newText = text.substring(index);
                    //textBoxRun.setText(newText);

                    // 插入图片到文本框中
                    String imageURL = "http://192.168.2.8/sgidi/signpic/ly/" + PartyIdCount + ".jpg"; // 图片地址
                    InputStream inputStream = new URL(imageURL).openStream();
                    textBoxRun.addPicture(inputStream, Document.PICTURE_TYPE_JPEG,
                            "signature.jpg", Units.toEMU(70), Units.toEMU(35)); // 图片宽度和高度

                    // 删除原始段落
                    document.removeBodyElement(document.getPosOfParagraph(paragraph));

                    found = true;
                    break;
                }
            }

            if (!found) {
                System.out.println("核准人未找到！");
            }

            // 保存修改后的 Word 文档
            FileOutputStream out = new FileOutputStream("modified-document.docx");
            document.write(out);
            out.close();
            document.close();

            System.out.println("签名图片已插入成功！");
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public static CTAnchor getAnchorWithGraphic(CTGraphicalObject ctGraphicalObject,
                                                String deskFileName, int width, int height,
                                                int leftOffset, int topOffset, boolean behind) {
        String anchorXML =
                "<wp:anchor  xmlns:wp=\"http://schemas.openxmlformats.org/drawingml/2006/wordprocessingDrawing\" "
                        + "simplePos=\"0\" relativeHeight=\"0\" behindDoc=\"" + ((behind) ? 1 : 0) + "\" locked=\"0\" layoutInCell=\"1\" allowOverlap=\"1\">"
                        + "<wp:simplePos x=\"0\" y=\"0\"/>"
                        + "<wp:positionH relativeFrom=\"column\">"
                        + "<wp:posOffset>" + leftOffset + "</wp:posOffset>"
                        + "</wp:positionH>"
                        + "<wp:positionV relativeFrom=\"paragraph\">"
                        + "<wp:posOffset>" + topOffset + "</wp:posOffset>" +
                        "</wp:positionV>"
                        + "<wp:extent cx=\"" + width + "\" cy=\"" + height + "\"/>"
                        + "<wp:effectExtent l=\"0\" t=\"0\" r=\"0\" b=\"0\"/>"
                        + "<wp:wrapNone/>"
                        + "<wp:docPr id=\"1\" name=\"Drawing 0\" descr=\"" + deskFileName + "\"/><wp:cNvGraphicFramePr/>"
                        + "</wp:anchor>";


        CTDrawing drawing = null;
        try {
            drawing = CTDrawing.Factory.parse(anchorXML);
        } catch (XmlException e) {
            e.printStackTrace();
        }
        CTAnchor anchor = drawing.getAnchorArray(0);
        anchor.setGraphic(ctGraphicalObject);
        return anchor;
    }


}
